package com.github.qianhe.sdk;

import java.util.Map;

/**
 * ReadServiceApi
 */
public class QHRead {

    private QHConfig config;
    private QHConstants.SignType signType;
    private boolean useSandbox;
    private QHRequest qhRequest;

    public QHRead(final QHConfig config) throws Exception {
        this(config, true);
    }

    public QHRead(final QHConfig config, final boolean useSandbox) throws Exception {
        this.config = config;
        this.useSandbox = useSandbox;
        if (useSandbox) {
            this.signType = QHConstants.SignType.MD5; // 沙箱环境
        } else {
            this.signType = QHConstants.SignType.HMACSHA256;
        }
//        this.qhRequest = new QHRequest(config);
    }

    /**
     * 验签 判断签名是否正确，必须包含sign字段，否则返回false。使用MD5签名。
     *
     * @param data Map类型数据
     * @return 签名是否正确
     * @throws Exception
     */
    public boolean verifySign(Map<String, String> data) throws Exception {
        return QHUtil.verifySign(data, this.config.getSecret());
    }

    /**
     * 请求千禾公共服务中心
     *
     * @param url
     * @param data
     * @return Map<String, String>
     */
    public Map request(String url, Map<String, String> data) throws Exception {
		/*
		app_key	是	string	渠道的key
		nonce_str	是	string	随机字符串，不长于32位
		time_stamp	是	string	时间戳（秒）
		sign	是	string	签名
		user_id
		*/
        data.put(QHConstants.FIELD_APPID, this.config.getAppID());
        data.put(QHConstants.FIELD_NONCE_STR, QHUtil.generateNonceStr());
        data.put(QHConstants.FIELD_TIME_STAMP, QHUtil.getCurrentTimestampStr());
        String sign = QHUtil.sign(data, this.config.getSecret());
        data.put(QHConstants.FIELD_SIGN, sign);
        String respJsonData = QHRequest.request(this.config.getQHDomain() + url, data);
        return QHUtil.Json.parse(respJsonData, Map.class);
    }

    /**
     * 查询阅读任务列表
     *
     * @param data
     * @return Map<String, String>
     */
    public Map<String, Object> getTaskList(Map<String, String> data) throws Exception {
        if(!data.containsKey("user_id")){
            throw new Exception("no param user_id");
        }
        return request(QHConstants.GET_TASK_LIST_URL_SUFFIX, data);
    }

    /**
     * 一键领取
     *
     * @param data
     * @return Map<String, String>
     */
    public Map<String, Object> getReadTask(Map<String, String> data) throws Exception {
        if(!data.containsKey("user_id")){
            throw new Exception("no param user_id");
        }
        return request(QHConstants.ONE_CLICK_COLLECTION_URL_SUFFIX, data);
    }
    /**
     * 更新异步任务完成通知地址
     *
     * @param data
     * @return Map<String, String>
     */
    public Map<String, Object> updateNotifyUrl(Map<String, String> data) throws Exception {
        if(!data.containsKey("notify_url")){
            throw new Exception("no param notify_url");
        }
        return request(QHConstants.UPDATE_NOTIFY_URL_SUFFIX, data);
    }
}
